<template>
  <BoTable ref="tableRef" :columns="columns" :request="_fetchList">
    <template #leftContainer>
      <div class="mr-4 w-48 border-r border-[rgba(255,255,255,.3)]">
        <div class="mr-2 flex h-10 items-center justify-between">
          <h3 class="module-title mb-0 mr-7">监测列表</h3>
        </div>
        <Tree
          :tree-data="treeData"
          :selected-keys="[selectKeys]"
          :expanded-keys="expandedKeys"
          :field-names="{ key: 'id', title: 'structureName' }"
        >
          <template #title="scope">
            <span @click="() => handleSelectStructure(scope)">{{
              scope.structureName
            }}</span>
          </template>
        </Tree>
      </div>
    </template>
  </BoTable>
  <Modal
    title="上传二维场景"
    v-model:open="visible"
    :mask-closable="false"
    :keyboard="false"
    destroy-on-close
    :footer="false"
  >
    <Upload2D :upload-request="uploadFile" @success="handleSuccess" />
  </Modal>

  <Dimensional
    v-model:open="previewData.visible"
    :src="previewData.src"
    :structure-name="previewData.structureName"
    :device-list="previewData.deviceList"
    keyboard
  ></Dimensional>

  <CropperModal></CropperModal>
</template>

<route lang="json">
{
  "meta": {
    "title": "二维场景"
  }
}
</route>

<script setup lang="tsx">
import { computed, onMounted, reactive, ref, useTemplateRef } from 'vue';
import { listToEnum, treeToArray } from '@boeyo/shared';
import { BoTable, BoTableProps } from '@boeyo/ui';
import { Modal, Tree, message } from 'ant-design-vue';
import { useRouter } from 'vue-router';
import Dimensional from '@/components/dimensional/index.vue';
import { useCropper } from '@/hooks/useCropper';
import {
  deleteMeasure,
  fetchList,
  fetchStructureTree,
  projectSelectList,
  uploadFile,
  uploadScene,
} from './api';
import Upload2D from './components/Upload2D.vue';

const router = useRouter();

const { CropperModal, open } = useCropper({
  width: 1080,
  height: 964,
  request: async (file: Blob) => {
    const formData = new FormData();
    formData.append('file', file);
    const result = await uploadFile(formData);
    await uploadScene({
      id: currentId.value,
      url: result.data.url,
    });
    tableRef.value.search();
    message.success('更新成功');
  },
});

const projectEnum = ref({});
const expandedKeys = ref([]);

onMounted(() => {
  projectSelectList().then((res) => {
    projectEnum.value = listToEnum(res.data, 'name', 'projectId');
  });
});

const treeData = ref();
onMounted(async () => {
  const result = await fetchStructureTree();
  treeData.value = result.data;
  expandedKeys.value = treeToArray(treeData.value).map((item) => item.id);
});

const _fetchList = (_params) => {
  return fetchList({ ...params, ..._params });
};

const selectKeys = ref(undefined);
const tableRef = useTemplateRef('tableRef');
let params: Record<string, any> = {};

const handleSelectStructure = (scope) => {
  const { monitoringType, id } = scope;
  params = {};
  if (id === selectKeys.value) {
    selectKeys.value = undefined;
  } else {
    selectKeys.value = id;
    switch (monitoringType) {
      case '1':
        params.netId = id;
        break;
      case '2':
        params.regionId = id;
        break;
      case '3':
        params.structureId = id;
        break;
    }
  }

  tableRef.value.refresh();
};

const columns = computed<BoTableProps['columns']>(() => {
  return [
    {
      title: '监测阵编号',
      dataIndex: 'monitoringCode',
    },
    {
      title: '监测阵名称',
      dataIndex: 'structureName',
    },
    {
      title: '关联项目',
      dataIndex: 'projectName',
      hideInSearch: true,
      // valueType: 'select',
      // valueEnum: projectEnum.value,
    },
    {
      title: '测点数量',
      dataIndex: 'pointCount',
      hideInSearch: true,
    },
    {
      title: '操作',
      hideInSearch: true,
      fixed: 'right',
      actions(opt) {
        return [
          {
            text: opt.record.photoUrl ? '更新' : '上传',
            onClick(record) {
              // onUpload(record);
              currentId.value = record.id;
              open({
                title: record.photoUrl ? '更新' : '上传',
                img: record.photoUrl,
              });
            },
          },
          {
            text: '预览',
            hidden: !opt.record.photoUrl,
            onClick(record) {
              handlePreview(record);
            },
          },
          {
            text: '删除二维场景',
            hidden: !opt.record.photoUrl,
            onClick(record) {
              Modal.confirm({
                title: '提示',
                content: '确认删除该场景的背景图及测点位置信息？',
                async onOk() {
                  await deleteMeasure(record.id);
                  message.success('操作成功');
                  tableRef.value.refresh();
                },
              });
            },
          },
        ];
      },
    },
  ];
});

const visible = ref(false);
const currentId = ref();
const onUpload = (record) => {
  currentId.value = record.id;
  visible.value = true;
};
const handleSuccess = async (data) => {
  await uploadScene({
    id: currentId.value,
    url: data.url,
  });
  visible.value = false;
  tableRef.value.search();
};

const previewData = reactive({
  visible: false,
  structureName: '',
  src: '',
  deviceList: [],
});
const handlePreview = async (data) => {
  // console.log(data);
  router.push({
    path: '/monitor/preview-2d',
    state: { ...data },
  });

  // const res = await preview(data.id);
  // console.log(res);

  // const { deviceTypes, pointList } = res.data;

  // previewData.deviceList = Object.keys(deviceTypes).map((key) => {
  //   return {
  //     label: deviceTypeEnum.value[key].text,
  //     value: deviceTypes[key],
  //   };
  // });
  // previewData.src = encodeURI(data.photoUrl);
  // previewData.structureName = data.structureName;
  // previewData.visible = true;
};
</script>
